<template>
    <div class="jx-course">
        <div>
            <h3 class="title">教学资源</h3>
            <div class="fileBox">
                <ul>
                    <li v-for="(item , index) in list" :key="index">
                         <img :src="item.iconPath" alt="">
                         <p class="typeName">{{item.showName}}</p>
                         <el-tooltip class="item" effect="light" :content="item.fileName" placement="right-start">
                            <p class="fileName">{{item.fileName}}</p>
                         </el-tooltip>
                        <p class="fileBtnBox">
                            <i class="iconfont icon-shangchuan" v-if='item.allowModify'><input id="version-file-input" type="file"  title='' @change="getFile($event,item.name)" /></i>
                            <i class="iconfont icon-xiazai" v-if="item.fileName && item.download==true"  style="color:#666666"  @click="downLoad(item.name,item.download,item.remark,item.fileName)"></i>
                            <i class="iconfont icon-xiazai drak" v-if="!item.fileName || item.download==false"></i>
                            <i class="iconfont icon-Group-" v-if="item.fileName && item.allowModify" @click="deleteFn(item.name)" ></i>
                        </p>
                    </li>
                </ul>
                <i class="clear-fix"></i>
            </div>
        </div>
        <div>
            <h3 class="title other">其他资源</h3>
            <div class="fileBox">
                <ul>
                    <div class="add fl" @click="add">
                        <i class='iconfont icon-jiahao'></i>
                    </div>
                    <li v-for="(item ,index) in otherList" :key="index">
                         <img :src="item.iconPath"  alt="">
                         <p class="typeName" v-text="item.name"></p>
                         <el-tooltip class="item" effect="light" :content="item.fileName" placement="right-start">
                            <p class="fileName" v-text="item.fileName"></p>
                        </el-tooltip>
                        <p class="fileBtnBox">
                            <a href="#"><i class="iconfont icon-xiazai download" v-if="item.download" @click="otherFile(item.remark,item.fileName)"></i></a>
                            <i class="iconfont icon-Group-" style="right:0px;top:-132px" @click="otherDelete(item.name,6)" v-if="roleId == 'TEACHER' || roleId == 'MARKET_TEACHER' "></i>
                            <i class="iconfont icon-Group-" style="right:0px;top:-116px" @click="otherDelete(item.name,6)" v-if="roleId == 'UNIVERSITY_TEACHER' "></i>
                            <i class="iconfont icon-xiazai drak" v-if="!item.fileName || !item.download"></i>
                            <i class="iconfont icon-Group-"  style="top:-129px" @click="otherDelete(item.name,6)" v-if="roleId == 'ADMIN' || roleId == 'INTERNET_ADMIN' || roleId == 'SUPER_ADMIN' "></i>
                        </p>
                    </li>
                </ul>
                <i class="clear-fix"></i>
            </div>
        </div>
         <el-dialog :close-on-click-modal="false"  title="添加资源" :visible.sync="dialogFormVisibles" width="500px" @close="closeTeacherDialog" >
            <el-form :model="form2" :rules="rules2" ref="form2">
                <el-form-item  label="资源名称 ：" prop="name">
                     <el-input v-model="form2.name" placeholder="请输入资源名称" maxlength="20" @input="dataInput"></el-input>
                     <p style="position:absolute;  left:260px; top: 12px;"> {{form2.num}}/20</p>
                </el-form-item>
                <el-form-item prop="versionFile" class="version-file">
                    <el-button class="button-style">上传文件<input id="versionInput" type="file"  title='' @change="getFile2"></el-button>
                    <span class='files' v-if="form2.versionFile.length>0">{{form2.versionFile}}</span>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" style="text-align:center;">
                <button class="button-style"  @click="saveForm('form2')">保 存</button>
            </div>
         </el-dialog>
    </div>
</template>
<script>
    export default{
        data(){
            return{
                //添加资源
                dialogFormVisibles:false,
                //预制资源
                dialogForm:false,
                // //文件名
                // versionFile:'',
                form2: {
                    fileName: '',
                    versionFile: '',
                    //上传文件名字
                    name:'',
                    //文件的字数控制
                    num:20
                },
                form: {
                    fileName: '',
                    versionFile: '',
                    //上传文件名字
                    name:'',
                    //文件的字数控制
                    num:0
                },
                //存储token值下载
                token:'',
                tokenAll:'',
                //身份
                roleId:'',
                //课程id
                courseId:'',
                //章节id
                chapterId:'',
                //教学资源数据集合
                list:[],
                //其他资源数据集合
                otherList:[],
                //其他资源数据集合
                preseList:[],
                rules2: {
                    versionFile: [
                        { required: true, message: '请上传文件', trigger: 'blur' }
                    ],
                    name: [
                        { required: true, message: '请输入资源名称', trigger: 'blur' }
                    ],
                }
            }
        },
        created () {
            this.roleId=this.$store.state.user.roles[0]
            this.chapterId = this.$localstorage.getLocalStorage('chapterInfoData').chapterId
            this.courseId = this.$localstorage.getLocalStorage('setCourseId')
            this.Teachinit()
        },
        methods: {
            //获取各种资源
            Teachinit(){
                this.public('5,6')
            },
            public(num){
                let self = this
                self.$http.get('/tes/course/'+ self.courseId+'/chapter/'+self.chapterId+'/make/resource?types='+num).then(response => {
                    let res = response.data
                    if(res.code == '200'){
                        self.list = res.data.learningResources.creativeVersion
                        self.otherList = res.data.otherResources.creativeVersion
                    // self.preseList = res.data.presetResource.creativeVersion
                    }else{
                        self.$message.error(res.message)
                    }
                })
            },
            //教学资源下载
            downLoad(name,download,remark,fileName){
                //专科版本有更改
                //此处需求：学习课件单独走下载接口，其他按照原来下载走
                let self = this
                if(name == '学习课件' && download){
                    // 二期更改 伟明写的因为有问题，暂时注释（李辛要求）
                    self.$http.post('/tes/course/'+self.courseId+'/chapter/'+self.chapterId+'/resource/file-download/permission',{
                        remark :remark,
                        fileName : fileName
                    }) .then(response => {
                        let res = response.data
                        if(res.code == '200'){
                            self.token = res.data
                            let downloadElement = document.createElement('a');
                            downloadElement.style.display = 'none';
                            downloadElement.href = '/tes/course/'+self.courseId+'/chapter/'+self.chapterId+'/resource/zip?token='+self.token
                            downloadElement.download = fileName; //下载后文件名
                            downloadElement.click(); //点击下载
                        }
                    })
                }else if(name != '学习课件' && download){
                    //专科版本
                    self.$http.post('/tes/course/'+self.courseId+'/chapter/'+self.chapterId+'/resource/file-download/permission',{
                        remark :remark,
                        fileName : fileName
                    }) .then((response) => {
                        let res = response.data
                        if(res.code == '200'){
                            self.token=res.data
                            let downloadElement = document.createElement('a');
                            downloadElement.style.display = 'none';
                            downloadElement.href = '/tes/course/'+self.courseId+'/chapter/'+self.chapterId+'/resource/file-download?token='+self.token
                            downloadElement.download = self.versionVideo; //下载后文件名
                            downloadElement.click(); //点击下载
                        }else{
                            self.$message.error(res.message)
                        }
                    })
                }
            },
            //下载方法
            commonFn(remark,fileName){
                let self = this
                self.$http.post('/tes/course/'+self.courseId+'/chapter/'+self.chapterId+'/resource/file-download/permission',{
                    remark :remark,
                    fileName : fileName
                }) .then((response) => {
                    let res = response.data
                    if(res.code == '200'){
                        self.tokenAll=res.data
                        let downloadElement = document.createElement('a');
                        downloadElement.style.display = 'none';
                        downloadElement.href = '/tes/course/'+self.courseId+'/chapter/'+self.chapterId+'/resource/file-download?token='+self.tokenAll
                        //downloadElement.download = self.versionVideo; //下载后文件名
                        downloadElement.click(); //点击下载
                    }else{
                        self.$message.error(res.message)
                    }
                })
            },
            //其他资源下载
            otherFile(remark,fileName){
                this.commonFn(remark,fileName)
            },
            //  //预制资源下载
            // preseListFile(remark,fileName){
            //     this.commonFn(remark,fileName)
            // },
            //教学资源删除
            deleteFn(item){
                let self = this;
                self.$confirm('是否确定删除?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    self.$http.post('/tes/course/'+self.courseId+'/chapter/'+self.chapterId+'/resource?resourceType=5',{
                        name:item
                    }).then((response) => {
                        let res = response.data
                        if(res.code == '200') {
                            self.$message({
                                message: '删除成功',
                                type: 'success'
                            })
                            self.Teachinit()
                            self.form2.versionFile =''
                            //window.location.reload()
                        }else{
                            self.$message.error(res.message)
                        }
                    }).catch(err => {
                        console.log(err)
                    })
                })
            },
            //删除预制资源
            // PreseDelete(item){
            //    this.CommonDelete(item,7)
            // },
            //删除其他资源
            otherDelete(item){
               this.CommonDelete(item,6)
            },
             //其他资源删除
            CommonDelete(item,num){
                let self = this;
                self.$confirm('是否确定删除?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                self.$http.post('/tes/course/'+self.courseId+'/chapter/'+self.chapterId+'/resource?resourceType='+num,{
                    name:item
                }).then((response) => {
                    let res = response.data
                    if(res.code == '200') {
                        self.$message({
                            message: '删除成功',
                            type: 'success'
                        })
                        self.Teachinit()
                        self.form.versionFile =''
                    }else{
                        self.$message.error(res.message)
                    }
                 }).catch(err => {
                     console.log(err)
                })
             })
            },
             //添加
            add(){
               this.dialogFormVisibles = true
               this.form2.num = 20
            },
            addFn(){
               this.dialogForm = true
               this.form.num = 0
            },
            //关闭弹窗
            closeTeacherDialog(){
               this.$refs.form2.resetFields()
               this.form2.name = ''
               this.form2.num = 20
            },
            closeDialogForm(){
                this.$refs.form.resetFields()
                this.form.name = ''
            },
            //教学资源上传文件
            getFile($event,item){
                let self = this
                let fileType = $event.target.files[0].name
                fileType = fileType.substring((fileType.lastIndexOf('.') + 1), fileType.length) //取得后缀名
                let fileSize =  $event.target.files[0].size
                let  size = fileSize/ 1024
                //console.log(item,99)
                if(item =='理论课学习视频'){
                    if(fileType.toLowerCase() != "mp4"){
                        self.$message.error('请上传mp4格式文件')
                        return
                    }
                }else if(item =='学习课件'){
                    if(fileType.toLowerCase() != "pptx" && fileType.toLowerCase() != "pdf"){
                        self.$message.error('请上传pptx格式文件或者pdf文件')
                        return
                    }
                }else if(item =='课程材料'){
                    if(fileType.toLowerCase() != "zip" && fileType.toLowerCase() != "rar"){
                        self.$message.error('请上传zip格式或者rar格式文件')
                        return
                    }
                    // if(size>500000){
                    //     this.$message.error('文件不能大于500MB,请重新选择！')
                    //     return
                    // }
                }else if(item =='随堂练习'|| item =='随堂练习答案'|| item =='备课材料'){
                    if(fileType.toLowerCase() != "docx" && fileType.toLowerCase() != "doc"){
                        self.$message.error('请上传 docx格式或者 doc格式文件')
                        return
                    }

                }else if(item =='实验课学习视频'){
                    if(fileType.toLowerCase() != "mp4"){
                        self.$message.error('请上传mp4格式文件')
                        return
                    }
                }
                // else if(item =='实验手册'){
                //     if(size>500000){
                //         this.$message.error('文件不能大于500MB,请重新选择！')
                //         return
                //     }
                // }
                 const loading = this.$loading({
                    lock: true,
                    text: '文件上传中...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                 })
                 let formData = new FormData();
                 formData.append('files', $event.target.files[0]);
                 this.$http.post('/tes/course/'+self.courseId+'/chapter/'+self.chapterId+'/resource-file?name='+item+'&resourceType=5', formData, {headers: {'Content-Type': 'multipart/form-data'}}).then((response) => {
                    let res = response.data
                    if(res.code == '200') {
                        this.$message({
                            message: '上传成功',
                            type: 'success'
                        })
                        loading.close()
                        $event.target.value=''
                        self.Teachinit()
                    }else if(res.code == '500'){
                        self.$message.error('上传失败，请检查文件中是否包含公式。若包含，请将公式转换为图片再上传')
                        loading.close()
                    }else{
                        loading.close()
                        $event.target.value=''
                        self.$message.error(res.message)
                    }
                }).catch(err => {
                    console.log(err)
                })
            },
            //上传文件
            getFile2($event) {
                let fileType = $event.target.files[0].name
                    fileType = fileType.substring((fileType.lastIndexOf('.') + 1), fileType.length)
                let fileSize =  $event.target.files[0].size
                let  size = fileSize/ 1024
                // if(size>500000){
                //     this.$message.error('文件不能大于500MB,请重新选择！')
                //     return
                // }
                this.form2.fileName = $event.target.files[0]
                this.form2.versionFile = $event.target.files[0].name
                $event.target.value=''
            },
            //上传文件
            fileUp($event){
                let fileType = $event.target.files[0].name
                     fileType = fileType.substring((fileType.lastIndexOf('.') + 1), fileType.length)
                let fileSize =  $event.target.files[0].size
                let  size = fileSize/ 1024
                // if(size>500000){
                //     this.$message.error('文件不能大于500MB,请重新选择！')
                //     return
                // }
                this.form.fileName = $event.target.files[0]
                this.form.versionFile = $event.target.files[0].name
                $event.target.value = ''
            },
            //上传其他文件
            saveForm(form2){
                let self = this
                let formData = new FormData()
                formData.append('files', self.form2.fileName);
				self.$refs[form2].validate((valid) => {
                    if (valid) {
                        const loading = this.$loading({
                            lock: true,
                            text: '文件导入中',
                            spinner: 'el-icon-loading',
                            background: 'rgba(0, 0, 0, 0.7)'
                        })
                        self.$http.post('/tes/course/'+self.courseId+'/chapter/'+self.chapterId+'/resource-file?name='+self.form2.name+'&resourceType=6', formData, {headers: {'Content-Type': 'multipart/form-data'}}).then((response) => {
                            let res = response.data
                            if(res.code == '200') {
                                self.$message({
                                    message: '上传成功',
                                    type: 'success'
                                })
                                loading.close()
                                self.Teachinit()
                                $('#versionInput').val('')
                                self.dialogFormVisibles = false
                                self.$refs[form2].resetFields()

                            }else{
                                loading.close()
                                self.$message.error(res.message)
                            }
                        })
                    }
                })
            },
            //其他字数
            dataInput(){
                var txtVal = this.form2.name.length;
                this.form2.num = 20 - txtVal
            },
            //预置资源字数
            dataInputNum(){
                var txtVal = this.form.name.length;
                this.form.num = 20 - txtVal
            }
        }
    }
</script>
<style scoped>
    .el-input{
        width: 200px;
    }
</style>
<style scoped lang="scss">
    @import "./../../../styles/ypublic.scss";
    .jx-course{
        width: 1200px;
        margin: 0 auto;
        background: #fff;
        padding: 30px;
        box-sizing: border-box;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
    }
    .title{
        font-size: $fs16;
        color: $title-gray;
        margin-bottom: 35px;
        font-weight: normal;
    }
    .other{
        margin-top: 30px
    }
    .fileBox{
        margin-left: 10px;
        border-bottom: 1px solid #e8e8e8;
    }
    .fileBox>ul>li{
        float: left;
        margin-right: 30px;
        height: 150px;
        width: 150px;
        text-align: center;
        margin-bottom: 28px;
        position: relative;
        &:hover{
            background: #f9f8f8;
            cursor: pointer;
            .fileBtnBox{
                display: block;
            }
        }
    }

    .fileBox>ul>li>img{
        margin-top: 25px;
        width: 50px;
        height: 50px;
    }
    .fileBox>ul>li .typeName{
        margin-top: 12px;
        font-size: $fs14;
        color: #727272;
    }
    .fileBox>ul>li .fileName{
        margin-top: 4px;
        text-align: center;
        padding: 0px 8px;
        font-size: $fs14;
        color: #727272;
        position: relative;
        overflow: hidden;
        white-space: nowrap;
        text-overflow:ellipsis;
        padding: 0 10px;
    }
    .fileBox>ul>li .fileBtnBox{
        position: absolute;
        bottom: 3px;
        left: 0;
        width: 100%;
        line-height: 12px;
        text-align: right;
        display: none;

    }
    .add{
        border: 1px dashed #d9d9d9;
        width: 140px;
        height: 140px;
        background: #fff;
        line-height: 140px;
        text-align: center;
        color: #8f8f8f;
        margin-right: 30px;
        border-radius: 8px;
        cursor: pointer;
        margin-bottom: 30px;
    }
    #versionInput{
        position: absolute;
        left: 2px;
        opacity: 0;
        top: 3px;
        width: 80px;
        height: 35px
    }
    #version-file-input{
        position: absolute;
        left: 96px;
        opacity: 0;
        top: 1px;
        width: 17px;
        font-size: 0px;
        height: 15px;
    }
    .download{
        right: 10px;
        bottom: 4px;
        position: absolute;
        color: #666666
    }
   .fileBox>ul>li .fileBtnBox>i{
       margin-right: 10px;
       cursor: pointer;
       font-size: 14px;
   }
   .drak{
        color: #d4d4d4
    }
   .dialog-footer{
       text-align: center;
   }
   .files{
       margin-left: 5px;
       margin-top: 5px;
   }
   .icon-Group-{
        position: absolute;
        top: -116px;
        right: 0px;
        cursor: pointer;
    }
</style>
